<template>
  <a-dropdown
    v-if="currentUser && currentUser.nickname"
    class="ant-pro-dropdown ant-pro-dropdown-action"
    placement="bottomRight"
    overlay-class-name="pro-components-header-dropdown-index-container"
  >
    <div>
      <div class="flex items-center">
        <a-avatar size="small" :src="currentUser.avatar" class="ant-pro-header-account-avatar" />
        <span class="ant-pro-header-account-name ml-8px">
          {{ currentUser.nickname }}
        </span>
      </div>
    </div>
    <template #overlay>
      <a-menu class="ant-pro-dropdown-menu" :selected-keys="[]">
        <a-menu-item v-if="menu" key="center" @click="handleToCenter">
          <template #icon><user-outlined /></template>
          个人中心
        </a-menu-item>
        <a-menu-item v-if="menu" key="settings" @click="handleToSettings">
          <template #icon><setting-outlined /></template>
          个人设置
        </a-menu-item>
        <a-menu-divider v-if="menu" />
        <a-menu-item key="logout" @click="handleLogout">
          <template #icon><logout-outlined /></template>
          退出登录
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
  <span v-else>
    <a-spin size="small" :style="{ marginLeft: 8, marginRight: 8 }" />
  </span>
</template>

<script lang="ts" setup>
import { UserOutlined, SettingOutlined, LogoutOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { loginRoutePath } from '@/router/define-meta';

defineProps({
  currentUser: {
    type: Object,
    default: () => null,
  },
  menu: {
    type: Boolean,
    default: true,
  },
});

const router = useRouter();
const userStore = useUserStore();
const handleToCenter = () => {
  router.push({ path: '/account/center' });
};
const handleToSettings = () => {
  router.push({ path: '/account/settings' });
};
const handleLogout = () => {
  userStore.LOGOUT().then(() => {
    location.replace(
      `${import.meta.env.VITE_APP_PUBLIC_PATH}${loginRoutePath}`.replaceAll('//', '/'),
    );
  });
};
</script>

<style lang="less">
body {
  @import './header-dropdown.less';
  .ant-pro-header-account-name {
    vertical-align: unset;
    color: @primary-color;
  }
  .ant-pro-header-account-avatar {
    margin: 12px 8px 12px 0;
    color: @primary-color;
    vertical-align: top;
    background: hsla(0deg, 0%, 100%, 0.85);
  }
}
</style>
